package cn.lixuan.controller;

import cn.lixuan.bo.RegistLoginBo;
import cn.lixuan.constants.BaseInfoProperties;
import cn.lixuan.grace.result.GraceJSONResult;
import cn.lixuan.grace.result.ResponseStatusEnum;
import cn.lixuan.pojo.Users;
import cn.lixuan.service.UserService;
import cn.lixuan.utils.IPUtil;
import cn.lixuan.utils.RedisOperator;

import cn.lixuan.utils.ValidateCodeUtils;
import cn.lixuan.vo.UsersVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.UUID;


@RestController
@Slf4j
@Api(tags = "用户登录注册接口")
@RequestMapping("passport")
public class PassportController {

    @Autowired
    private RedisOperator redis;

    @Autowired
    private UserService userService;

    @ApiOperation(value = "发送短信验证码")
    @PostMapping("getSMSCode")
    public GraceJSONResult getSMSCode(@RequestParam String mobile, HttpServletRequest request) {
        // 得用户ip，限制用户在60秒内只能获得一次验证码
        String userIp = IPUtil.getRequestIp(request);
        redis.setnx60s(BaseInfoProperties.MOBILE_SMSCODE + userIp, userIp);

        // 把验证码放到redis中，用于后续的验证
        String code = ValidateCodeUtils.generateValidateCode(6).toString();
        redis.set("SMS_CODE_" + mobile, code, 30*60);
        log.info(code); //测试阶段不发送验证码

//        SMSUtils.sendMessage(mobile, code);
        return GraceJSONResult.ok();
    }

    @ApiOperation(value = "用户注册登录")
    @PostMapping("login")
    public GraceJSONResult Login(@Valid @RequestBody RegistLoginBo registLoginBo) {

        String mobile = registLoginBo.getMobile();
        String code = registLoginBo.getSmsCode();

        String redisCode = redis.get("SMS_CODE_" + mobile);

        // 判断验证码是否为空或者错误
        if(StringUtils.isBlank(redisCode) || !redisCode.equalsIgnoreCase(code)) {
            return GraceJSONResult.errorCustom(ResponseStatusEnum.SMS_CODE_ERROR);
        }

        // 查询用户是否存在
        Users user = userService.queryMobileIsExist(mobile);
        if(user == null) {
            user = userService.createUser(mobile);
        }

        // 保存用户会话信息
        String uToken = UUID.randomUUID().toString();
        redis.set(BaseInfoProperties.REDIS_USER_TOKEN + user.getId(), uToken);

        // 用户注册成功后删除redis中的短信验证码
        redis.del("SMS_CODE_" + mobile);

        // 返回用户信息，包含token
        UsersVO usersVO = new UsersVO();
        BeanUtils.copyProperties(user, usersVO);
        usersVO.setUserToken(uToken);

        return GraceJSONResult.ok(usersVO);
    }


    @ApiOperation(value = "退出登录")
    @PostMapping("logout")
    public GraceJSONResult Logout(@RequestParam String userId) {

       // 后端清除用户的token信息即可
        redis.del(BaseInfoProperties.REDIS_USER_TOKEN + userId);

        return GraceJSONResult.ok();
    }
}
